import codecs
from urllib.request import *


def write_request_result(request_data, response_data):
	'''
	将请求结果写到文件中
	:param request_data:  请求数据
	:param response_data:  响应数据
	:return: none
	'''
	f = open('result.txt', 'a', True)
	response_data = str(response_data, encoding="utf-8")
	f.writelines('\n')
	f.writelines((request_data, '---------', response_data))
	f.writelines('\n')


def get_web_content(url_path, request_data):
	'''
	请求数据
	:param url: url
	:param request_data: 数据
	:return: 请求结果
	'''
	print('当前查询数据为-->' + request_data)
	param = "{\"content\":\"" + request_data + "\",\"query\": \"尊敬的辖区居民，您好，我是市政府12345服务热线的工作人员，为了您的健康，请您配合调查，通话完全保密，请您放心。请问您近期有没有去过外省，例如湖北、武汉、黑龙江、韩国、日本等\"}"
	param = param.encode('UTF-8')
	req = Request(url=url_path, data=param, method='POST')
	user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
	req.add_header('Content-Type', 'application/json')
	req.add_header('Accept', 'application/json')
	req.add_header('User-Agent', user_agent)
	with urlopen(req, timeout=60) as result:
		data = result.read()
		write_request_result(request_data, data)


if __name__ == '__main__':
	line_array = []
	with codecs.open("test.txt", 'r', 'utf-8') as original_test_file:
		for line in original_test_file:
			line = line.strip('\r\n')
			line_array.append(line)
			if not line:
				break
	for inner in line_array:
		get_web_content('http://47.94.85.6:1260/800031/47epidemicAI', inner)
